package lei.m_线程池_事物;

/**
 * @className: SingleThreadWithResult
 * @author: xl
 * @date: 2025/7/26 16:23
 * @Version: 1.0
 * @description:
 */

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class SingleThreadWithResult {

    public static void main(String[] args) {
        //1. Main方法本身就是单线程执行
        System.out.println("主程序开始");

        // 创建Callable任务
        Callable<String> task = new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("=== Main方法中的线程信息 ===");
                System.out.println("线程名称: " + Thread.currentThread().getName());
                System.out.println("线程ID: " + Thread.currentThread().getId());
                System.out.println("是否是主线程: " + (Thread.currentThread().getName().equals("main")));

                // 模拟复杂计算
                int result = 0;
                for (int i = 1; i <= 10; i++) {
                    result += i;
                    System.out.println("计算进度: " + i + "/10");

                    Thread.sleep(500);// 模拟计算耗时0.5秒
                }

                System.out.println("任务线程完成计算");
                return "计算结果: " + result;
            }
        };

        // 使用FutureTask包装Callable
        FutureTask<String> futureTask = new FutureTask<>(task);

        // 创建并启动线程
        Thread thread = new Thread(futureTask, "Calculator-Thread");
        thread.start();

        // 获取执行结果
        try {
            String result = futureTask.get(); // 阻塞等待结果
            System.out.println("任务执行结果: " + result);
            System.out.println("主程序结束");
        } catch (Exception e) {
            System.err.println("获取结果失败: " + e.getMessage());
        }
    }
}


